import React, { Component } from 'react'
import { connect } from 'react-redux'
import ValidProjectName from 'graphql/org/ValidProjectName.graphql'
import UpdateProject from 'graphql/project/config/updateProject.graphql'
import QueryProject from 'graphql/project/queryOneProject.graphql'
import deleteDataset from 'graphql/dataset/deleteDataset.graphql'
import { PaddingContainer } from 'components/containers'
import { ValidType } from 'components/validForm'
import {
  Form as FormTable, Section as TableSection, Input, Submit,
} from 'components/tableForm'
import { global as globalDuck } from 'ducks'
import { push, replace } from 'connected-react-router'

const getVariables = values => ({
  name: values.name.value,
  description: values.description.value,
})

class ProjectBasicConfig extends Component {
  componentDidMount = () => {
    const { setParentActiveItem } = this.props
    setParentActiveItem('basic')
  }

  render() {
    const { project, link, reLink } = this.props
    const {
      projectId, orgId, projectName, orgName,
    } = project
    const mailRule = [
      {
        type: ValidType.REGULAR,
        value: /^[\s\S]*.*[^\s][\s\S]*$/,
        errorMessage: '项目名称不能为空',
      },
      {
        type: ValidType.REGULAR,
        value: /^[\u4E00-\u9FA5A-Za-z0-9_]+$/,
        errorMessage: '项目名称由中文、英文数字包括下划线',
      },
      {
        type: ValidType.REMOTE,
        value: {
          query: ValidProjectName,
          params: { ownerId: orgId },
        },
        errorMessage: '该项目已经存在于你的账户',
        getResult: re => re.project.length === 0,
      },
    ]
    const descriptionRule = [
      {
        type: ValidType.MAXLENGTH,
        value: 1000,
        errorMessage: '项目名称长度不超过1000个字符',
      },
    ]
    const deleteRule = [
      {
        type: ValidType.EQ,
        value: projectName,
        errorMessage: `应输入: ${projectName}`,
      },
    ]
    return (
      <PaddingContainer>
        <FormTable
          initQuery={{
            query: QueryProject,
            variables: { id: projectId },
            tableName: 'project',
          }}
        >
          <TableSection header="编辑数据集名称">
            <Input
              name="name"
              header="数据集名称"
              description="存储空间名称由 4 ~ 63 个字符组成 ，可包含 字母、数字、中划线。"
              rules={mailRule}
            />
          </TableSection>
          <Submit
            submit={{
              text: '保存',
              variables: { pid: projectId },
              getVariables,
              mutation: UpdateProject,
              success: (data) => {
                link('/empty')
                setTimeout(() => {
                  if (data && data.update_project && data.update_project.returning) {
                    const newName = data.update_project.returning[0].name
                    reLink(`/project/${orgName}/${newName}/config/basic`)
                  }
                })
              },
            }}
            cancle={{ text: '取消', url: `/project/${orgName}/${projectName}/config/basic` }}
            validFields={['name']}
            redirect
          />
          <TableSection header="编辑数据集描述">
            <Input
              textArea
              name="description"
              header="数据集描述"
              description="项目名称长度不超过1000个字符"
              rules={descriptionRule}
            />
          </TableSection>
          <Submit
            submit={{
              text: '保存',
              variables: { pid: projectId },
              getVariables,
              mutation: UpdateProject,
              success: (data) => {
                link('/empty')
                setTimeout(() => {
                  if (data && data.update_project && data.update_project.returning) {
                    const newName = data.update_project.returning[0].name
                    reLink(`/project/${orgName}/${newName}/config/basic`)
                  }
                })
              },
            }}
            cancle={{ text: '取消', url: `/project/${orgName}/${projectName}` }}
            validFields={['description']}
            redirect
          />
          <TableSection header="危险操作区" red>
            <Input
              name="deleteName"
              header="删除项目"
              description={`为了安全起见请您输入当前要删除的项目名称：${projectName}`}
              rules={deleteRule}
              red
            />
          </TableSection>
          <Submit
            submit={{
              text: '删除',
              variables: { id: projectId },
              getVariables: () => {},
              mutation: deleteDataset,
              success: () => {
                link('/empty')
                setTimeout(() => {
                  reLink(`/org/${orgName}/dataset`)
                })
              },
            }}
            validFields={['deleteName']}
            red
          />
        </FormTable>
      </PaddingContainer>
    )
  }
}

const mapStateToProps = state => ({
  user: globalDuck.selectors.user(state),
})

const mapDispatchToProps = {
  link: push,
  reLink: replace,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(ProjectBasicConfig)
